package com.gsj.web.controller;

import com.gsj.domain.company.Company;
import com.gsj.domain.module.Module;
import com.gsj.domain.user.User;
import com.gsj.service.module.ModuleService;
import com.gsj.service.user.UserService;
import com.gsj.web.basecrotonller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;


import java.util.List;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    /*@RequestMapping("/login")
    public String login(String email,String password){

        if(email==null||password==null){
            request.setAttribute("error","用户名或者密码不能为空");
            return "forward:/login.jsp";
        }
        User user=userService.findByEmail(email);
        if (user!=null){
            if(user.getPassword().equals(password)){
                request.getSession().setAttribute("loginUser",user);
                List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
                request.getSession().setAttribute("moduleList",moduleList);
                return "home/main";
            }

        }
        request.setAttribute("error","用户名或者密码错误");
        return "forward:/login.jsp";

    }*/

    @RequestMapping("/login")
    public String login(String email,String password){

        if(email==null||password==null){
            request.setAttribute("error","用户名或者密码不能为空");
            return "forward:/login.jsp";
        }
        try {
            //创建shiro的subject对象，表示当前请求
            Subject subject=SecurityUtils.getSubject();
            //创建token对象，封装帐号密码
            AuthenticationToken token= new UsernamePasswordToken(email,password);
           //登录认证，如果登录失败直接抛异常（在realm中认证）
            subject.login(token);
            User user= (User) subject.getPrincipal();
            request.getSession().setAttribute("loginUser",user);
            List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
            request.getSession().setAttribute("moduleList",moduleList);
            return "home/main";

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","用户名或密码错误！");
            return "forward:/login.jsp";
        }
    }


@RequestMapping("/home")
    public String home(){
        return "home/home";
    }
    @RequestMapping("logout")
    public String logout(){
        httpSession.removeAttribute("loginUser");
        httpSession.invalidate();
        return "forward:/login.jsp";
    }
}
